package com.bytz.modules.cms.c4c.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import com.bytz.common.exception.BytzBootException;
import com.bytz.common.util.RedisUtil;
import com.bytz.modules.cms.c4c.model.*;
import com.bytz.modules.cms.c4c.service.IC4cFeignService;
import com.bytz.modules.cms.c4c.sync.C4cOdataFeign;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class C4CFeignServiceImpl implements IC4cFeignService {

    @Autowired
    private C4cOdataFeign c4cOdataFeign;

    @Autowired
    private RedisUtil redisUtil;

    public static final String FORMAT = "json";

    public static final String END_USER_LAST_SYNC_TIME_KEY = "c4c:end_user_last_sync_time";

    @Override
    public List<C4cCustomer> getSoldToAndShipTo() {
        String lastSyncTime = (String) redisUtil.get(END_USER_LAST_SYNC_TIME_KEY);
        String currentDateTime = LocalDateTimeUtil.format(LocalDateTime.now(ZoneId.of("GMT")), "yyyy-MM-dd'T'HH:mm:ss.SSSSSSS'Z'");
        String select = "AccountID,ExternalID,Name,FormattedPostalAddressDescription,Mobile,Email";

        StringBuilder filter = new StringBuilder();
        // 状态为active
        filter.append("LifeCycleStatusCode eq '2' ");
        // TODO 时间筛选有问题后续优化
//        if (lastSyncTime != null) {
//            filter
//                    .append("and EntityLastChangedOn ge datetimeoffset'")
//                    .append(lastSyncTime)
//                    .append("'");
//        }

        String skipToken = null;
        // 每次查1000条，把对应的数据全查回来
        List<C4cCustomer> customers = new ArrayList<>();
        do {
            C4cResponse<List<C4cCustomer>> endUserResponse = c4cOdataFeign.getCorporateAccountCollection(FORMAT, select, filter.toString(), skipToken);
            customers.addAll(endUserResponse.getData().getResults());
            skipToken = endUserResponse.getData().getSkipToken();
        } while (skipToken != null);
        redisUtil.set(END_USER_LAST_SYNC_TIME_KEY, currentDateTime);
        return customers;
    }

    @Override
    public List<C4cOpportunity> getOpportunityBySalesAndSoldTo(String saleBusinessPartnerId, String soldToId) {
        return c4cOdataFeign.getOpportunityCollection(
                FORMAT,
                "ID,ObjectID,Name,ProspectPartyName",
                "ProspectPartyID eq '" + soldToId + "' and MainEmployeeResponsiblePartyID eq '" + saleBusinessPartnerId + "' and (LifeCycleStatusCode eq '1' or LifeCycleStatusCode eq '2')"
        ).getData().getResults();
    }

    @Override
    public SalesQuoteIds getQuoteReference(String opportunityId, String quotationId) {

        SalesQuoteIds result = new SalesQuoteIds();

        // 根据c4c报价id查询 sap报价id(RelationshipRoleCode eq '6') 和 C4C Order ID(RelationshipRoleCode eq '2')
        C4cResponse<List<C4cSalesQuoteReference>> quoteResponse = c4cOdataFeign.getSalesQuoteReferenceCollection(
                FORMAT,
                "QuoteID,ID,RelationshipRoleCode",
                "QuoteID eq '" + quotationId + "'"
        );
        Map<String, String> typeIdMap = quoteResponse.getData().getResults().stream()
                .collect(Collectors.toMap(C4cSalesQuoteReference::getRelationshipRoleCode, C4cSalesQuoteReference::getId));

        // sap 报价id
        result.setSapQuotationId(typeIdMap.get("6"));
        // c4c order id
        result.setC4cSalesOrderId(typeIdMap.get("2"));

        // 如果c4c销售订单id不为空则查询sap订单id
        if (StringUtils.isNotBlank(result.getC4cSalesOrderId())){
            String filter = "SalesOrderID eq '%s' and TypeCode eq '2059'and RoleCode eq '6'";
            String sapOrderId  = c4cOdataFeign.getSapOrder(FORMAT, "SalesOrderID,ID", String.format(filter, result.getC4cSalesOrderId())).getData().getResults()
                    .stream().findFirst().orElse(new C4cBusinessTransactionDocument()).getId();
            result.setSapSalesOrderId(sapOrderId);
        }

        return result;
    }

    @Override
    public C4cOpportunity getOpportunityById(String opportunityId) {
        C4cResponse<List<C4cOpportunity>> result = c4cOdataFeign.getOpportunityCollection(
                FORMAT,
                "",
                "ID eq '" + opportunityId + "'"
        );
        return result.getData().getResults().stream().findFirst().orElseThrow(() -> new BytzBootException("找不到对应的opportunity"));
    }

    @Override
    public C4cProductAndHierarchy getProductAndHierarchy() {
        // TODO: feng 等同步商品的接口
        return null;
    }

    @Override
    public C4cOpportunity createOpportunity(C4cOpportunity opportunity) {
        C4cXmlOpportunityResponse response = c4cOdataFeign.postOpportunityCollection(opportunity);
        BeanUtils.copyProperties(response.getContent().getProperties(), opportunity);
        return opportunity;
    }

    /**
     * 在c4c中创建一条报价单
     */
    @Override
    public C4cSalesQuote createSalesQuote(C4cSalesQuote salesQuote) {
        C4cXmlSalesQuoteResponse response = c4cOdataFeign.postSalesQuoteCollection(salesQuote);
        BeanUtils.copyProperties(response.getContent().getProperties(), salesQuote);
        return salesQuote;
    }



    /**
     * 查询所有enderUser中文名称
     * TODO 目前查询的是所有的 等c4c接口出来改为时间筛选
     */
    @Override
    public List<C4cChineseName> getEndUserChineseName(){
        String skipToken = null;
        // 每次查1000条，把对应的数据全查回来
        List<C4cChineseName> customers = new ArrayList<>();
        do {
            C4cResponse<List<C4cChineseName>> chineseNameResponse = c4cOdataFeign.getQueryChineseName("AccountID,BusinessPartnerFormattedName,CountryCodeText,StateCode,StateCodeText,City,District,StreetPostalCode,AddressLine1,Street", "InternationalVersionCode eq 'C'", skipToken, "json");
            customers.addAll(chineseNameResponse.getData().getResults());
            skipToken = chineseNameResponse.getData().getSkipToken();
        } while (skipToken != null);

        return customers;
    }

    /**
     * 项目订单将机会和报价单关联
     * @param objectId 报价单的objectId
     * @param opportunityId 机会id
     * @return
     */
    @Override
    public C4cQuoteOpportunity relationQuoteOpportunity(String objectId, String opportunityId){
        C4cQuoteOpportunity c4cQuoteOpportunity = new C4cQuoteOpportunity();
        c4cQuoteOpportunity.setId(opportunityId);
        C4cXmlCreateY2Response response = c4cOdataFeign.postRelationQuoteOpportunity(objectId, c4cQuoteOpportunity);
        BeanUtils.copyProperties(response.getContent().getProperties(), c4cQuoteOpportunity);
        return c4cQuoteOpportunity;

    }


    /**
     *
     * @param objectId 报价单的objectId
     * @return
     */
    @Override
    public C4cOrderItem createProduct(String objectId){
        C4cOrderItem c4cOrderItem = new C4cOrderItem();
        C4cXmlOrderItemResponse response = c4cOdataFeign.postCreateProduct(objectId, c4cOrderItem);
        BeanUtils.copyProperties(response.getContent().getProperties(), c4cOrderItem);
        return c4cOrderItem;

    }

    @Override
    public void updateOpportunityProbability(String opportunityObjectId) {
        C4cOpportunity opportunity = new C4cOpportunity();
        opportunity.setResultReasonCode("Z14");
        opportunity.setLifeCycleStatusCode("4");
        c4cOdataFeign.patchOpportunityCollection(opportunityObjectId, opportunity);
    }
}
